<template>
    <div>
        <el-row>
            <el-col style=" display:flex;   " :span="24"> <el-form :inline="true" :model="form"
                    class="demo-form-inline">

                    <el-form-item label="肺部患病情况">
                        <el-select v-model="form.type" placeholder="请选择肺部患病情况" clearable>
                            <el-option label="正常肺部" :value="0" />
                            <el-option label="轻微肺炎" :value="1" />
                            <el-option label="严重肺炎" :value="2" />
                        </el-select>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="onSubmit">搜索</el-button>
                        <el-button type="warning" @click="onReset">重置</el-button>
                    </el-form-item>
                </el-form></el-col>
        </el-row>
        <el-row>
            <el-col style=" display:flex; justify-content: center;" :span="24">
                <el-card style="width:100%">
                    <template #header>
                        <div style="display:flex;justify-content:space-between; align-items: center;">


                            <span style="font-weight: 600;">CT影像数据</span>
                            <div style="display: flex; align-items: center;"> <el-button :disabled="!isOver"
                                    @click="trainData()" type="success">{{ isOver ? '开始训练' : `训练中 ${djsText}` }}
                                </el-button>
                                <el-button @click="handleEdit()" type="primary">新增</el-button>
                            </div>

                        </div>
                    </template>
                    <el-table :data="result.list" :height="sheight + 'px'" style="width: 100%">
                        <el-table-column prop="name" label="影像名称" align="center" width="auto" />
                        <el-table-column prop="type" label="影像类型" align="center" width="auto">
                            <template #default="scope">
                                <el-tag v-if="scope.row.type == 0" type="success">
                                    正常肺部
                                </el-tag>
                                <el-tag v-if="scope.row.type == 1" type="warning">
                                    轻微肺炎
                                </el-tag>
                                <el-tag v-if="scope.row.type == 2" type="danger">
                                    严重肺炎
                                </el-tag>

                            </template>
                        </el-table-column>
                        <el-table-column prop="url" label="影像图片" align="center" width="auto">
                            <template #default="scope">

                                <el-image style="width: 100px; height: 100px" :src="baseUrl + scope.row.url"
                                    :zoom-rate="1.2" :max-scale="7" preview-teleported :min-scale="0.2"
                                    :preview-src-list="[baseUrl + scope.row.url]" fit="cover">
                                    <template #error>
                                        <div class="image-slot">

                                            <el-icon><icon-picture /></el-icon>
                                        </div>
                                    </template></el-image>

                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="操作">
                            <template #default="scope">
                                <el-button type="primary" @click="handleEdit(scope.row._id)">
                                    修改
                                </el-button>
                                <el-popconfirm @confirm="handleDelete(scope.row._id)" @cancel="() => { }"
                                    title="确定删除此记录?">
                                    <template #reference>
                                        <el-button type="danger"> 删除 </el-button>
                                    </template>
                                </el-popconfirm>
                            </template>
                        </el-table-column>
                    </el-table>
                    <template #footer>
                        <div style="width: 100%; display: flex; justify-content: flex-end">
                            <el-pagination v-model:current-page="params.pageNumber" v-model:page-size="params.pageSize"
                                :page-sizes="[10, 50, 100]" background layout="sizes, prev, pager, next"
                                :total="result.total" @size-change="handleSizeChange"
                                @current-change="handleCurrentChange" />
                        </div>
                    </template>
                </el-card>
            </el-col>
        </el-row>
    </div> <el-dialog v-model="visible" :show-close="false" width="500">
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <div :id="titleId" :class="titleClass">CT影像信息</div>
                <el-button type="danger" @click="close">
                    <el-icon class="el-icon--left">
                        <CircleCloseFilled />
                    </el-icon>
                    Close
                </el-button>
            </div>
        </template>
        <el-form :rules="formRules" label-width="auto" :model="uForm" ref="sform" style="max-width: 600px">
            <el-form-item v-if="uForm._id" label="影像编号">
                <el-input v-model="uForm._id" disabled />
            </el-form-item>
            <el-form-item label="影像名称" prop="name">
                <el-input v-model="uForm.name" />
            </el-form-item>
            <el-form-item label="肺部患病情况" prop="type">
                <el-select v-model="uForm.type" placeholder="请选择肺部患病情况" clearable>
                    <el-option label="正常肺部" :value="0" />
                    <el-option label="轻微肺炎" :value="1" />
                    <el-option label="严重肺炎" :value="2" />
                </el-select>
            </el-form-item>

            <el-form-item label="影像图片" prop="url">
                <el-upload action="#" @change="change" v-if="hfileList.length == 0" list-type="picture-card"
                    v-model:file-list="fileList" :auto-upload="false">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>
                <div v-else style="width: 150px; height: 150px; position: relative">
                    <div @click="handleRemove()"
                        style="width:20px; height: 20px;background:red; cursor:pointer; color:  white; display:flex;justify-content: center; align-items: center; position: absolute; right: 0; top: 0">
                        <el-icon>
                            <Delete />
                        </el-icon>
                    </div>
                    <img style="width: 150px; height: 150px" :key="hfileList" :src="hfileList[0].url" alt="" />
                </div>
            </el-form-item>
            <div style="width:100%;display:flex;justify-content: center; "> <el-button type="primary"
                    @click="submit">提交</el-button></div>

        </el-form>
    </el-dialog>
</template>

<script setup lang="ts">
import { getPicList, getPic, deletePic, addPic, modifyPic, upload as Iupload, train } from '@/api';
import { onMounted, onUnmounted, ref, getCurrentInstance } from 'vue'
import { CircleCloseFilled } from "@element-plus/icons-vue";
import { Picture as IconPicture, Plus, Delete } from "@element-plus/icons-vue";
import storage from '@/storage';
import dayjs from 'dayjs';
const { proxy } = getCurrentInstance() as any
const params = ref({
    pageNumber: 1,
    pageSize: 10,
})
const handleRemove = () => {
    fileList.value = []
    hfileList.value = []
};
const form = ref<any>({
    type: '',
})
const onReset = () => {
    form.value = {}
    init()
}
const trainData = () => {
    ElMessage.success("训练开始");
    storage.set('end', new Date().getTime() + 1000 * 60 * 12);
    train()
}
const formRules = ref<any>({
    name: [
        {
            required: true,
            message: '请输入账号',
            trigger: 'blur',
        },
    ],
    type: [
        {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
        },
    ],
    url: [{
        validator: (rule: any, value: any, callback: any) => {
            if (hfileList.value.length == 0) {

                return callback(new Error('请上传图片'))
            }
            return true
        }, trigger: 'blur'
    }],
})
const handleDelete = (id: string) => {
    deletePic({ id: id })
        .then((res) => {
            if (res.code == 200) {
                ElMessage.success("删除成功");
                init();
            } else {
                ElMessage.error("删除失败");
            }
        })
        .catch(() => {
            ElMessage.error("删除错误");
        });
};
const handleSizeChange = () => {
    init();
};
const handleCurrentChange = () => {
    init();
};

const fileList = ref<any>([

]); const hfileList = ref<any>([

]);
const change = (file: any) => {
    const formdata = new FormData()
    formdata.append('file', file.raw)
    Iupload(formdata).then((res: any) => {
        hfileList.value = [{ url: baseUrl.value + res.url, uploadUrl: res.url, name: "food.jpeg" }];

    })

};
const visible = ref(false)
const submit = () => {
    proxy.$refs.sform.validate((valid: any) => {
        if (valid) {
            if (uForm.value._id) {
                //修改逻辑
                try {
                    modifyPic(Object.assign({}, { ...uForm.value }, { url: hfileList.value[0].uploadUrl })).then(res => {
                        if (res.code == 200) {
                            ElMessage.success("修改成功");
                            visible.value = false
                            init();
                        } else {
                            ElMessage.error("修改失败");
                        }
                    }).finally(() => {
                        uForm.value = {};
                        hfileList.value = []
                        fileList.value = []
                    })
                } catch (error) {
                    ElMessage.error("修改错误");
                }
            } else {
                //新增逻辑
                try {
                    addPic(Object.assign({}, { ...uForm.value }, { url: hfileList.value[0].uploadUrl ? hfileList.value[0].uploadUrl : "" })).then(res => {
                        if (res.code == 200) {
                            ElMessage.success("新增成功");
                            visible.value = false
                            init();
                        } else {
                            ElMessage.error("新增失败");
                        }
                    }).catch(err => {
                        console.log(err)
                    }).finally(() => {
                        uForm.value = {}
                        hfileList.value = []
                        fileList.value = []
                    })
                } catch (error) {
                    ElMessage.error("新增错误");
                }
            }
        }
    })


}
const uForm = ref<any>({
    name: "",
    type: ""
});

const handleEdit = (id?: string) => {
    if (id) {
        //修改逻辑
        try {
            getPic({ id: id }).then(res => {
                if (res.code == 200) {
                    uForm.value = res.data
                    hfileList.value = [{ url: baseUrl.value + uForm.value.url, uploadUrl: res.url, name: "food.jpeg" }];
                } else {

                }
            })
        } catch (error) {
        }
    } else {

    }
    visible.value = true
}
const sheight = ref(0)
const result = ref<any>({})
const baseUrl = ref(import.meta.env.VITE_URL);
const win = () => {
    setTimeout(() => {
        let t = document.querySelector('.el-page-header') as HTMLDivElement
        let f = document.querySelector('.el-form') as HTMLDivElement
        let z = document.querySelector('.el-card__header') as HTMLDivElement
        let x = document.querySelector('.el-card__footer') as HTMLDivElement
        let a = window.innerHeight
        sheight.value = a - t.offsetHeight - f.offsetHeight - z.offsetHeight - x.offsetHeight - 70
    }, 40);
}
onMounted(() => {
    window.addEventListener('resize', win)
})
onUnmounted(() => {
    window.removeEventListener('resize', win)
})
const djsText = ref("")
const timer = ref<any>(null)
const isOver = ref<boolean>(false)
const count = () => {
    let endTime = +storage.get('end');
    let startTime = +new Date().getTime()

    console.log(startTime, endTime);


    if (endTime - startTime > 0) {
        isOver.value = false
    } else {
        isOver.value = true
    }
    console.log(dayjs(endTime - startTime).format("mm:ss"));
    djsText.value = dayjs(endTime - startTime).format("mm:ss")
}

timer.value = setInterval(() => {
    count()
}, 1000);
onUnmounted(() => {
    clearInterval(timer.value)
    timer.value = null
})
// count()

const init = () => {

    win();
    getPicList(Object.assign({}, params.value, form.value)).then(res => {
        result.value = res.data
    })
}
init()

const onSubmit = () => {
    getPicList(
        Object.assign({}, params.value, form.value)
    ).then((res: any) => {
        if (res.code == 200) {
            result.value = res.data;
            ElMessage.success("搜索成功");
        }
    });
}
</script>

<style scoped>
.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}

.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}

.image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
}
</style>